using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ICSharpCode.WinFormsUI.Controls.NodeControls
{
	public class NodeIcon : BindableControl
	{
		public override Size MeasureSize(NTreeNode node)
		{
			Image image = GetIcon(node);
			if (image != null)
				return image.Size;
			else
				return Size.Empty;
		}

		public override void Draw(NTreeNode node, DrawContext context)
		{
			Image image = GetIcon(node);
			if (image != null)
			{
				Point point = new Point(context.Bounds.X,
					context.Bounds.Y + (context.Bounds.Height - image.Height) / 2);
				context.Graphics.DrawImage(image, point);
			}
		}

		protected virtual Image GetIcon(NTreeNode node)
		{
            if (node.Tree != null && node.Tree.ImageList != null)
            {
                Image image = null;
                if (node.IsSelected)
                {
                    if(node.SelectedImageIndex != -1)
                    {
                        image = node.Tree.ImageList.Images[node.SelectedImageIndex];
                        if (image != null)
                            return image;
                    }

                    if (node.Tree.SelectedImageIndex != -1)
                    {
                        image = node.Tree.ImageList.Images[node.Tree.SelectedImageIndex];
                        if (image != null)
                            return image;
                    }                   
                }

                if(node.ImageIndex != -1)
                {
                    image = node.Tree.ImageList.Images[node.ImageIndex];
                    if (image != null)
                        return image;
                }

                if(node.Tree.ImageIndex != -1)
                {
                    image = node.Tree.ImageList.Images[node.Tree.ImageIndex];
                    if (image != null)
                        return image;
                }              

            }
			return GetValue(node) as Image;
		}
	}
}
